const vscode = require('vscode');

// 定义 ezOne-[数字编号] 匹配的正则表达式
const ezOneRegex = /ezOne-(\d+)/g;

/**
 * 注册 ezOne ID 的文档链接提供者
 * @returns {vscode.Disposable}
 */
function registerEzOneLinkProvider() {
    return vscode.languages.registerDocumentLinkProvider(
        { language: 'markdown', scheme: 'file' },
        {
            provideDocumentLinks(document) {
                const links = [];
                const text = document.getText();
                let match;

                ezOneRegex.lastIndex = 0; // 重置正则的 lastIndex
                while ((match = ezOneRegex.exec(text)) !== null) {
                    const issueNumber = match[1];
                    const startPos = document.positionAt(match.index);
                    const endPos = document.positionAt(match.index + match[0].length);
                    const range = new vscode.Range(startPos, endPos);

                    // ***** 关键修改：将外部链接改为命令 URI *****
                    // 构造命令 URI，传递 issueNumber 作为参数
                    // 需要对参数进行 JSON.stringify 和 encodeURIComponent 处理
                    const commandArgs = encodeURIComponent(JSON.stringify([issueNumber]));
                    const targetUri = vscode.Uri.parse(`command:extension.showEzOneOptions?${commandArgs}`);

                    links.push(new vscode.DocumentLink(range, targetUri));
                }
                return links;
            }
        }
    );
}

function registerShowEzOneOptions() {
    let disposable = vscode.commands.registerCommand('extension.showEzOneOptions', async (issueNumber) => {
        // issueNumber 是从 DocumentLink 传递过来的参数
        // showQuickPick 用于弹出下拉选择框
        // 读取目录以及分支
        const workspaces = [
            { path: '/Users/mac/Desktop/ezone/frontend', name: '工作区一', },
            { path: '/Users/mac/Desktop/ezone/frontend-2', name: '工作区二', },
            { path: '/Users/mac/Desktop/ezone/frontend-3', name: '工作区三', },
            { path: '/Users/mac/Desktop/ezone/admin', name: '管理后台', }
        ]
        const branchMap = {}
        for (let { path } of workspaces) {
            // 进入path读取当前分支
            const branch = await new Promise((resolve, reject) => {
                require('child_process').exec(`cd ${path} && git branch --show-current`, (error, stdout) => {
                    if (error) {
                        reject(error)
                    } else {
                        resolve(stdout.trim())
                    }
                })
            })
            branchMap[path] = branch
        }
        const selectedOption = await vscode.window.showQuickPick(
            [
                { label: `🔗 查看详情`, type: 'openUrl' },
                ...workspaces.map(({ path, name }) => {
                    const currBranch = branchMap[path]
                    const branchIsIssue = currBranch === `ezOne-${issueNumber}`
                    let rs = `📂 ${name}`
                    rs += ` 分支: ${currBranch}`
                    if (branchIsIssue) {
                        rs += ` ✅`
                    }
                    let description = ''
                    if (String(currBranch).startsWith('ezOne-')) {
                        const activeEditor = vscode.window.activeTextEditor; // 获取当前激活的编辑器
                        if (activeEditor) {
                            const document = activeEditor.document; // 这就是document对象的来源
                            for (let i = 0; i < document.lineCount; i++) {
                                const line = document.lineAt(i);
                                if (line.text.includes(currBranch)) {
                                    // 仅有一个ezOne
                                    if (line.text.split('ezOne-').length > 2) {
                                        continue;
                                    }
                                    const sps = [':', ';', '--']
                                    description = `${line.text.split(currBranch)[1]}`
                                    for (let sp of sps) {
                                        const index = description.indexOf(sp);
                                        if (index !== -1) {
                                            description = description.slice(0, index).trim();
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    return {
                        label: rs,
                        type: 'openProject',
                        path: path,
                        description
                    }
                }),
                { label: '🦀 发起评审', type: 'createReview' },
                { label: '👀 查看评审', type: 'openReview' },
                { label: '🔨 合入dev', type: 'mergeToDev' },
                { label: '📋 复制内容', type: 'copyContent' },
            ],
            {
                placeHolder: `选择一个关于 ezOne-${issueNumber} 的操作`
            }
        );

        console.log(selectedOption);

        if (selectedOption) {
            // 根据用户的选择执行不同的操作
            if (selectedOption.type === 'openUrl') {
                const externalUri = vscode.Uri.parse(`https://ezone.ezone-i.work/project/ezOne/${issueNumber}`);
                vscode.env.openExternal(externalUri); // 在外部浏览器打开链接
            }
            if (selectedOption.type === 'openProject') {
                const path = selectedOption.path
                const cmd = `code ${path}`

                require('child_process').exec(cmd, (error, stdout) => {
                    if (error) {
                        console.error(`执行命令 ${cmd} 失败：${error}`)
                    } else {
                        console.log(`执行命令 ${cmd} 成功：${stdout}`)
                        // 复制内容 `ezOne-${issueNumber}`
                        vscode.env.clipboard.writeText(`ezOne-${issueNumber}`)
                    }
                })
            }
            if (selectedOption.type === 'copyContent') {
                // 获取光标所在行内容
                const activeEditor = vscode.window.activeTextEditor; // 获取当前激活的编辑器
                if (activeEditor) {
                    const document = activeEditor.document; // 这就是document对象的来源
                    const cursorPosition = activeEditor.selection.active; // 获取光标位置
                    const line = document.lineAt(cursorPosition.line); // 获取光标所在行内容
                    let content = line.text.trim();
                    // 去掉前面部分无关内容
                    content = 'ezOne-' + issueNumber + content.split(issueNumber)[1];
                    // 去掉后面的内容
                    const sps = [':', ';', '--']
                    for (let sp of sps) {
                        const index = content.indexOf(sp);
                        if (index !== -1) {
                            content = content.slice(0, index).trim();
                            break;
                        }
                    }
                    vscode.env.clipboard.writeText(content);
                    vscode.window.showInformationMessage(`已复制内容：${content}`);
                }
            }
            // 发起评审，https://ezone.ezone-i.work/code/ezone/frontend/-/reviews/_new?src=${issueNumber}
            if (selectedOption.type === 'createReview') {
                const externalUri = vscode.Uri.parse(`https://ezone.ezone-i.work/code/ezone/frontend/-/reviews/_new?src=ezOne-${issueNumber}`);
                vscode.env.openExternal(externalUri); // 在外部浏览器打开链接
            }
            if (selectedOption.type === 'openReview') {
                const externalUri = vscode.Uri.parse(`https://ezone.ezone-i.work/code/ezone/frontend/-/reviews?query=ezOne-${issueNumber}`);
                vscode.env.openExternal(externalUri); // 在外部浏览器打开链接
            }
            if (selectedOption.type === 'mergeToDev') {
                const externalUri = vscode.Uri.parse(`https://ezone.ezone-i.work/code/ezone/frontend/-/compare/dev/ezOne-${issueNumber}?tab=srcRef`);
                vscode.env.openExternal(externalUri); // 在外部浏览器打开链接
            }
        }
    });
    return disposable;
}

module.exports = {
    registerEzOneLinkProvider,
    registerShowEzOneOptions,
};